﻿var hasChecked = false;
//isDouble 如果双击一条数据的时候，就设置为空。这样是为了防止
var isDouble = false;


function setCurrentDate() {
    var curr_time = new Date();
    var strDate = curr_time.getFullYear() + "-";
    strDate += curr_time.getMonth() + 1 + "-";
    strDate += curr_time.getDate() + " ";
    strDate += curr_time.getHours() + ":";
    strDate += curr_time.getMinutes() + ":";
    strDate += curr_time.getSeconds();
    $("#Date").datebox("setValue", strDate);

    var currentDate = curr_time.getFullYear() + "-";
    currentDate += curr_time.getMonth() + 1 + "-";
    currentDate += curr_time.getDate();
    $("#dateto").datebox("setValue", currentDate);

    var before2Yeas = curr_time.getFullYear() - 2 + "-";
    before2Yeas += curr_time.getMonth() + 1 + "-";
    before2Yeas += curr_time.getDate();
    $("#datefrom").datebox("setValue", before2Yeas);

}

function setSearcherItems() {
    url = "../Handlers/OtherHanders/GetRequiredFromFile.ashx?type=s";
    $.get(url, function (data) {
        if (data != "-1") {
            var lists = data.split(';');
            for (var i = 0; i < lists.length; i++) {
                var chbInput = document.getElementsByName(lists[i])[0];
                if (chbInput.type == "checkbox") {
                    chbInput.checked = true;
                }
            }
        }
    });
}

$(function () {
    setDisabled();
    setCurrentDate();
    setSearcherItems();


    $('#ShopName').combobox({
        editable: false,
        method: 'post',
        url: '../Handlers/ShopManagerHandler.ashx?action=getall'
    });

    $('#allShops').combobox({
        editable: false,
        method: 'post',
        url: '../Handlers/ShopManagerHandler.ashx?action=getall',
        onLoadSuccess: function () { //加载完成后,设置选中第一项
            var val = $(this).combobox("getData");
            for (var item in val[0]) {
                if (item == "ShopID") {
                    $(this).combobox("select", val[0][item]);
                }
            }
        }
    });

    $('#allUsers').combobox({
        editable: false,
        method: 'post',
        url: '../Handlers/UserHandler/GetUserHandler.ashx',
        onLoadSuccess: function () { //加载完成后,设置选中第一项
            var val = $(this).combobox("getData");
            for (var item in val[0]) {
                if (item == "UserID") {
                    $(this).combobox("select", val[0][item]);
                }
            }
        }
    });
    var count = 0;
    $('#Register').datagrid({
        title: '登记记录',
        url: '../Handlers/RegisterHandler/GetRegisterHandler.ashx',
        singleselect: true,
        method: 'post',
        idField: 'id',
        width: 'auto',
        height: 'auto',
        loadMsg: '数据加载中请稍后……',
        columns: cols,
        pagination: true,
        onBeforeLoad: function (param) {
        },
        onLoadSuccess: function (data) {
            $("#txtTotalCash").val(data.totalMoney);
            $("#txtOrderCount").val("订单：" + data.total);
        },
        onLoadError: function () {
        },
        onClickCell: function (rowIndex, field, value) {
        },
        onDblClickRow: function () {
            isDouble = true;
            var row = $('#Register').datagrid('getSelected');
            if (row) {
                url = "../Handlers/RegisterHandler/UpdateRegisterHandler.ashx?id=" + row.ProID + "&OldQQRelation=" + row.QQRelation;
                $('#newRegisterDlg').dialog('open').dialog('setTitle', '更新');
                $('#fm').form('clear');
                //$("#province").append("<option selected='selected' value='" + row.Province + "'>" + row.Province + "</option>");
                $("#province option[text='" + row.Province + "']").attr("selected", true);
                $("#city").append("<option selected='selected' value='" + row.City + "'>" + row.City + "</option>");
                $("#district").append("<option selected='selected' value='" + row.District + "'>" + row.District + "</option>");
                $("#beizhu").val(row.Beizhu);
                $('#fm').form('load', row);
            }
        },
        rowStyler: function (index, row) {

            //Can working...
            //            if (row.ShopID == '2') {
            //                return 'background-color:red;color:blue;font-weight:bold;';
            //            }
            //            else if (row.ShopID == '14') {
            //                return 'background-color:yellow;color:blue;font-weight:bold;';
            //            }
            //            //Can working...

            //            var myStyle = '';
            //            var myUrl = '../Handlers/RegisterHandler/color.ashx';
            //            var jsonStr = '';

            //            if (count == 0) {
            //                $.post(myUrl, function (data) {
            //                    count += 1;
            //                    jsonStr = eval('(' + data + ')');
            //                });
            //            }

            //            var dicArray = new Array();

            //            for (var o in jsonStr) {
            //                var temp = jsonStr[o].ShopID;
            //                dicArray[temp] = jsonStr[o].ShopColor;

            //            }
            //alert("jsonStr.length: " + jsonStr.length);
            //            for (var j = 0; j < jsonStr.length; j++) {
            //                var temp = jsonStr[j].ShopID;
            //                dicArray[temp] = jsonStr[j].ShopColor;
            //                   alert(temp + ' ' + dicArray[temp]);
            //            }
            // alert('dicArray.length: ' + dicArray.length);


            //            for (var i in dicArray) {
            //                if (i == row.ShopID) {
            //                    return 'background-color:' + dicArray[i] + ';color:blue;font-weight:bold;';
            //                }
            //            }

            //            f
            //            alert('Row.ShopID' + row.ShopID);
            //            for (var i = 0; i < dicArray.length; i++) {
            //                alert(dicArray[i]);
            //            }
            //            if (row.ShopID == '2') {
            //                return 'background-color:' + dicArray[2] + ';color:blue;font-weight:bold;';
            //            }
            //            else if (row.ShopID == '14') {
            //                return 'background-color:' + dicArray['14'] + ';color:blue;font-weight:bold;';
            //            }


            //alert("Row.ShopID: " + row.ShopID);
            //            for (var o in jsonStr) {
            //                //alert("jsonStr[o].ShopID: " + jsonStr[o].ShopID);
            //                if (jsonStr[o].ShopID == row.ShopID) {
            //                    // alert(jsonStr[o].ShopID + "====> " + row.ShopID);
            //                    return 'background-color:' + jsonStr[o].ShopColor + ';color:blue;font-weight:bold;';
            //                }
            //            }

            //return myStyle;
        }

    });
})



function LighterFont(val, font) {
    if (!!font) {
        val = val + "";
        if (val == $.trim(font)) {
            val = val.replace($.trim(font), '<span style=" background-color:gray; font-weight:bold; font-size:large">' + $.trim(font) + '</span>');
            return val;
        }
    }
    return val;

}


var createGridHeaderContextMenu = function (e, field) {
    e.preventDefault();
    var grid = $(this); /* grid本身 */
    var headerContextMenu = this.headerContextMenu; /* grid上的列头菜单对象 */
    if (!headerContextMenu) {
        var tmenu = $('<div style="width:100px;"></div>').appendTo('body');
        var fields = grid.datagrid('getColumnFields');
        for (var i = 0; i < fields.length; i++) {
            var fildOption = grid.datagrid('getColumnOption', fields[i]);
            if (!fildOption.hidden) {
                $('<div iconCls="icon-ok" field="' + fields[i] + '"/>').html(fildOption.title).appendTo(tmenu);
            } else {
                $('<div iconCls="icon-empty" field="' + fields[i] + '"/>').html(fildOption.title).appendTo(tmenu);
            }
        }
        headerContextMenu = this.headerContextMenu = tmenu.menu({
            onClick: function (item) {
                var field = $(item.target).attr('field');
                if (item.iconCls == 'icon-ok') {
                    grid.datagrid('hideColumn', field);
                    $(this).menu('setIcon', {
                        target: item.target,
                        iconCls: 'icon-empty'
                    });
                } else {
                    grid.datagrid('showColumn', field);
                    $(this).menu('setIcon', {
                        target: item.target,
                        iconCls: 'icon-ok'
                    });
                }
            }
        });
    }
    headerContextMenu.menu('show', {
        left: e.pageX,
        top: e.pageY
    });
};
$("#Register").datagrid.defaults.onHeaderContextMenu = createGridHeaderContextMenu;


var url;
function newRegister() {

    setRequirField();
    ClearExistVal();
    ResetDate();
    isDouble = false;
    var keyword = $("#keyword").val();
    if ($.trim(keyword) != "") {
        var arry = keyword.split('\n');

        //判定是第一种模式 还是第二种模式以及第三种模式！~ 严格判定。
        var isFirstMode = arry[0].indexOf('QQ') == 0 && arry[1].indexOf('旺旺') == 0 && arry[2].indexOf('银行户名') == 0 && arry[3].indexOf('银行账号') == 0 && arry[4].indexOf('何种银行') == 0;
        var isSecondMode = arry[0].indexOf('QQ') == 0 && arry[1].indexOf('旺旺') == 0 && arry[2].indexOf('旺旺绑定支付宝') == 0 && arry[3].indexOf('支付宝名字') == 0 && arry[4].indexOf('返款财付通') == 0;
        var isThridMode = arry[0].indexOf('QQ') == 0 && arry[1].indexOf('旺旺') == 0 && arry[2].indexOf('旺旺绑定支付宝') == 0 && arry[3].indexOf('支付宝名字') == 0 && arry[4].indexOf('返款银行卡及户名') == 0 && arry[5].indexOf('何种银行') == 0;

        if (isFirstMode || isSecondMode || isThridMode) {
            for (var i = 0; i < arry.length; i++) {
                var v = arry[i];
                var infoSplit = v.split(':');
                if (infoSplit.length > 0) {
                    v = v.replace(':', '：');
                }
                var Info = v.split('：');
                if (Info.length > 1) {
                    AutoFillByKeywords($.trim(Info[0]), $.trim(Info[1]));
                }
            }

            $('#newRegisterDlg').dialog('open').dialog('setTitle', '新增登记');
            url = '../Handlers/RegisterHandler/AddRegisterHandler.ashx';
        }
        else {
            $.messager.alert('提示:', '搜索关键字 里面的格式不正确。请检查格式或者清空里面的数据，在点击"新增登记"按钮!');
        }
    }
    else {

        $('#newRegisterDlg').dialog('open').dialog('setTitle', '新增登记');
        url = '../Handlers/RegisterHandler/AddRegisterHandler.ashx';
    }
}

function ResetDate() {
    var curr_time = new Date();
    var strDate = curr_time.getFullYear() + "-";
    strDate += curr_time.getMonth() + 1 + "-";
    strDate += curr_time.getDate() + " ";
    strDate += curr_time.getHours() + ":";
    strDate += curr_time.getMinutes() + ":";
    strDate += curr_time.getSeconds();
    $("#Date").datebox("setValue", strDate);
}

function copyRegister() {
    var row = $('#Register').datagrid('getSelected');
    if (row == null) {
        jQuery.messager.alert('提示:', '请选择一条要登记的记录！');
        return;
    }
    if (row.Wangwang == "" || row.ShopName == "") {
        jQuery.messager.alert('提示:', '该条数据旺旺或者店名为空，不能登记，请完善数据再试！');
        return;
    }
    //----2014.7.13 modify start
    var url2 = "../Handlers/RegisterHandler/RegisterDate.ashx?qq=" + row.QQ + "&shop=" + row.ShopName;
    var isOK;
    $.post(url2, function (data) {
        if (data == "true") {
            isOK = "true";
        }
        else if (data == "error") {
            isOK = "error";
        }
        else {
            isOK = "false";
        }
    });

    if (isOK == "true") {
        $.messager.confirm('警告', '相同QQ+相同店铺15天内已录入一条数据，您仍然要录入该数据吗？?', function (r) {
            if (r) {
                BeginCopyRegister(row);
            }
        });
    }
    else if (isOK == "false") {
        BeginCopyRegister(row);
    }
    else {
        jQuery.messager.alert('登记提示', '登记失败！');
    }
}


function BeginCopyRegister(row) {
    var u = $("#webCurrentUserName").val();
    url = "../Handlers/RegisterHandler/CopyRegisterHandler.ashx?uWangwang=" + row.Wangwang + "&u=" + u + "&qq=" + row.QQ + "&pid=" + row.ProID + "&uShopName=" + row.ShopName;
    $('#fm').form('submit', {
        url: url,
        onSubmit: function () {
        },
        success: function (result) {
            var result = eval('(' + result + ')');
            if (result.errorMsg) {
                jQuery.messager.alert('登记提示', '登记失败！' + result.errorMsg);
            } else {
                jQuery.messager.alert('登记提示', '登记成功！');
                $('#newRegisterDlg').dialog('close');        // close the dialog
                $('#Register').datagrid('reload');    // reload the user data
            }
        }
    });
}



function deleteRegister() {
    var row = $('#Register').datagrid('getSelected');
    $("#txtPasswords").val("");
    if (row) {
        document.getElementById("bg2").style.display = "block";
        document.getElementById("myConfirmPasswordDiv").style.display = "block";
    }
    else {
        alert("请选定一条数据，谢谢。");
    }
}

function GetPasswordByUser() {
    var row = $('#Register').datagrid('getSelected');
    var user = document.getElementById("webCurrentUserName").value;
    var pass = document.getElementById("txtPasswords").value;
    if (pass != "") {
        url = "../Handlers/UserHandler/GetPasswordByUserName.ashx?username=" + user + "&password=" + pass + "&id=" + row.ProID;
        $.messager.confirm('确认', '您确定要删除该条记录吗?', function (r) {
            if (r) {
                $.post(url, function (result) {
                    if (result == "success") {
                        var msg = "成功删除 QQ 为[" + row.QQ + "]的数据！";
                        alert(msg);
                        $('#Register').datagrid('reload');    // reload the user data
                    } else {
                        alert("密码不正确，请重试！");
                    }
                });
            }
        });
        document.getElementById("bg2").style.display = 'none';
        document.getElementById("myConfirmPasswordDiv").style.display = 'none';
    }
    else {
        alert("密码不能为空");
    }
}

function setRequirField() {
    url = "../Handlers/OtherHanders/GetRequiredFromFile.ashx?type=r";
    $.get(url, function (data) {
        var allList = data.split(';');
        for (var i = 0; i < allList.length; i++) {
            $("#" + allList[i]).validatebox({
                required: true
            });
        }
    });
}

function saveSearchProjects() {
    var allInputs = document.getElementsByTagName("input");
    var sb = "";
    for (i = 0; i < allInputs.length; i++) {
        if (allInputs[i].checked) {
            sb += allInputs[i].value + ";";
        }
    }
    url = "../Handlers/OtherHanders/HandlerSeacherProjects.ashx?val=" + sb;
    $.get(url, function (data) {
        alert(data);
    });
}

function saveRegister() {
    var isNull = false;
    var qq = $("#QQ").val();
    var shopid = $('#ShopName').combobox('getValue');
    var url2 = "../Handlers/RegisterHandler/RegisterDate.ashx?qq=" + qq + "&shop=" + shopid;
    var isOK;
    $.post(url2, function (data) {
        if (data == "true") {
            isOK = true;
        }
        else {
            isOK = false;
        }
    });
    if (isDouble) {
        RegisterData();
    }
    else {
        if (isOK) {
            $.messager.confirm('警告', '相同QQ+相同店铺15天内已录入一条数据，您仍然要录入该数据吗？?', function (r) {
                if (r) {
                    RegisterData();
                }
            });
        } else {
            RegisterData();
        }
    }
}
//function HanderlUrl() {
//    var kw = $("#keyword").val();
//    var kws = kw.split('\n');
//    var str = "";
//    for (var i = 0; i < kws.length; i++) {
//        str += kws[i] + "|";
//    }
//    return str;
//}
function RegisterData() {
    //var newUrl = HanderlUrl();
    var queryParams = $('#Register').datagrid('options').queryParams;
    //    queryParams.keywords = $("#keyword").val();
    //    queryParams.isSearch = "yes";

    var keyword = $.trim($("#keyword").val());
    var datefrom = $("#datefrom").datebox("getValue");
    var dateto = $("#dateto").datebox("getValue");
    var pricefrom = $.trim($("#pricefrom").val());
    var priceto = $.trim($("#priceto").val());
    var queryParams = $('#Register').datagrid('options').queryParams;
    var limitdays = $.trim($("#LimitDays").val());
    var ShopName = $('#ShopName').combobox('getValue');
    var shopId = $('#allShops').combobox('getValue');
    var userName = $('#allUsers').combobox('getText');
    if (allSearcherItems != "-1") {
        hasChecked = true;
    }
    else {
        hasChecked = false;
    }
    queryParams.hasChecked = hasChecked;
    queryParams.isSearch = "yes";
    queryParams.keywords = keyword;
    queryParams.datefrom = datefrom;
    queryParams.dateto = dateto;
    queryParams.pricefrom = pricefrom;
    queryParams.priceto = priceto;
    queryParams.limitdays = limitdays;
    queryParams.chkqq = $("#QQ").val();
    queryParams.chbzhifubaoname = $("#ZhifubaoName").val();
    queryParams.searchScope = allSearcherItems;
    queryParams.shopId = shopId;
    queryParams.userName = userName;
    queryParams.isDirectAddRegisterFlag = "yes";
    if (ShopName == "") {
        jQuery.messager.alert("错误提示", "店铺不能为空！");
        return;
    }


    $('#fm').form('submit', {
        url: url,
        onSubmit: function () {
            return $(this).form('validate');
        },
        success: function (result) {
            var result = eval('(' + result + ')');
            if (result.errorMsg) {
                jQuery.messager.alert("失败提示", result.errorMsg);
            } else {
                jQuery.messager.alert("成功提示", "你已经成功添加或修改了登记数据！");
                $('#newRegisterDlg').dialog('close');        // close the dialog
                $('#Register').datagrid('options').queryParams = queryParams;
                $('#Register').datagrid('reload');    // reload the user data
                //$("#Register").datagrid('reload');
            }
        }
    });
}

$.ajaxSetup({
    async: false
});

var allSearcherItems = null;
function getSearchProjectFromConfigFile() {
    url = "../Handlers/OtherHanders/GetRequiredFromFile.ashx?type=s";
    $.get(url, function (data) {
        allSearcherItems = data;
    });
}
function Search() {
    getSearchProjectFromConfigFile();
    ReloadGrid();
}


function getscope() {
    var qq = $("#chbqq").val();
    return qq;
}

function ReloadGrid() {

    var keyword = $.trim($("#keyword").val());
    var datefrom = $("#datefrom").datebox("getValue");
    var dateto = $("#dateto").datebox("getValue");
    var pricefrom = $.trim($("#pricefrom").val());
    var priceto = $.trim($("#priceto").val());
    var queryParams = $('#Register').datagrid('options').queryParams;
    var limitdays = $.trim($("#LimitDays").val());
    var shopId = $('#allShops').combobox('getValue');
    var userName = $('#allUsers').combobox('getText');
    if (allSearcherItems != "-1") {
        hasChecked = true;
    }
    else {
        hasChecked = false;
    }

    queryParams.hasChecked = hasChecked;
    queryParams.isSearch = "yes";
    queryParams.keywords = keyword;
    queryParams.datefrom = datefrom;
    queryParams.dateto = dateto;
    queryParams.pricefrom = pricefrom;
    queryParams.priceto = priceto;
    queryParams.limitdays = limitdays;
    queryParams.chkqq = $("#chbQQ").attr("checked") == "checked" ? "1" : "";
    queryParams.chbcaifutong = $("#chbcaifutong").attr("checked") == "checked" ? "1" : ""; ;
    queryParams.chbcaifutongname = $("#chbcaifutongname").attr("checked") == "checked" ? "1" : "";
    queryParams.chbzhifubaoname = $("#chbrebatename").attr("checked") == "checked" ? "1" : "";
    queryParams.chbzhifubaoaccount = $("#chbrebatezhifubao").attr("checked") == "checked" ? "1" : "";
    queryParams.chbfkzhifubaoname = $("#chbfkzhifubaoname").attr("checked") == "checked" ? "1" : "";
    queryParams.chbfkzhifubao = $("#chbfkzhifubao").attr("checked") == "checked" ? "1" : "";
    queryParams.searchScope = allSearcherItems;
    queryParams.shopId = shopId;
    queryParams.userName = userName;
    queryParams.isSourceQuery = document.getElementById("chbSourceQuery").checked;
    if (queryParams.isSourceQuery.toString() == "true" && queryParams.keywords.trim() == "") {
        alert("请在搜索关键字框中输入‘来源’信息");
        return;
    }

    hidediv();
    $('#Register').datagrid('options').queryParams = queryParams;
    $("#Register").datagrid('reload');
}

function showdiv() {
    document.getElementById("bg").style.display = "block";
    document.getElementById("show").style.display = "block";
}
function hidediv() {
    document.getElementById("bg").style.display = 'none';
    document.getElementById("show").style.display = 'none';

    document.getElementById("bg2").style.display = 'none';
    document.getElementById("myConfirmPasswordDiv").style.display = 'none';

}

function importCheck() {
    var file = document.getElementById("fAddress");
    if (file.value == "") {
        jQuery.messager.alert('提示:', '请选择文件！');
        return false;
    }
}


function Import() {
    if (importCheck() == false) {
        return;
    }
    url = "../Handlers/RegisterHandler/ImportRegisterHandler.ashx?filepath=" + document.getElementById("fAddress").value;
    $('#fm').form('submit', {
        url: url,
        onSubmit: function () {
            //  return $(this).form('validate');
        },
        success: function (result) {
            var result = eval('(' + result + ')');
            if (!!result.exist) {
                jQuery.messager.alert('提示:', '该数据最近一次的登记日期是：' + result.updatedate + '!');
                return;
            }
            if (result.errorMsg) {
                $.messager.show({
                    title: 'Error',
                    msg: result.errorMsg
                });
            } else {
                jQuery.messager.alert('提示:', '登记成功！');
                $('#newRegisterDlg').dialog('close');        // close the dialog
                $('#Register').datagrid('reload');    // reload the user data
            }
        }
    });
}


function importCheck() {
    var file = document.getElementById("fAddress");
    if (file.value == "") {
        jQuery.messager.alert('提示:', '请选择文件！');
        return false;
    }
}
//Set the QQ CheckBox to "True".
function setQQCheckIsTrue() {
    var obj = document.getElementById("chbBankName");
    if (obj.checked) {
        $("#chbQQ").attr("checked", true);
    }
}


$.extend($.fn.validatebox.defaults.rules, {
    Rebatezhifubao: {
        validator: function (value, para) {
            return value.length > 0 || para.length > 0;
        },
        message: '支付宝或者财付通有一项不能为空！'
    }
});